﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyEngineExercise.我的扩展;
using ESRI.ArcGIS.Geodatabase;
using System.Diagnostics;
using MyEngineExercise.工作.分割图层_20120810;
using ESRI.ArcGIS.Geometry;
using MyEngineExercise.我的扩展.信息类;

namespace MyEngineExercise
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// 基准地价系统某一功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 分割图层20120810ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            #region 打开shp或mdb文件,保存为featureClass
            OpenFileDialog openfileDialog = new OpenFileDialog();
            openfileDialog.InitialDirectory = "E:\\";
            openfileDialog.Filter = "shapefile文件|*.shp|mdb文件|*.mdb";
            openfileDialog.Title = "打开shp或mdb";
            IFeatureClass featureClass = null;
            if (openfileDialog.ShowDialog() == DialogResult.OK)
            {
                //Debug.Print("shapefile路径为：" + openfileDialog.FileName);
                if (System.IO.Path.GetExtension(openfileDialog.FileName) == ".shp")
                {
                    Debug.Print("打开了shp。");
                    featureClass = MyAeMethods.Instance.NewFeatureClass(openfileDialog.FileName);
                }
                else if (System.IO.Path.GetExtension(openfileDialog.FileName) == ".mdb")
                {
                    Debug.Print("打开了mdb。");
                re_write_fc_name:
                    Form_write_featureclass_name form_write_featureclass_name = new Form_write_featureclass_name();
                    if (form_write_featureclass_name.ShowDialog() == DialogResult.OK)
                    {
                        //MessageBox.Show(form_write_featureclass_name.Get_fc_name); return;
                        try
                        {
                            featureClass = MyAeMethods.Instance.NewMdbFeatureWorkspace(openfileDialog.FileName).OpenFeatureClass(form_write_featureclass_name.Get_fc_name);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show("找不到featureClass，请检查featureClass是否存在？大小写有没有错？名称是否有空格？\n" + ex.Message);
                            goto re_write_fc_name;
                        }

                    }
                    else
                        return;

                }

            }
            else
                return;
            #endregion

            //合并多边形
            //IPolygon unionPolygon = MyAeMethods.Instance.UnionPolygons(featureClass);
            IPolygon unionPolygon = featureClass.UnionPolygons(null);

            #region 创建shapefile，确定一下是否合并为我想要的样子
            /*//要求用户输入红线的非空间信息
            InputRedLineInfoForm inputRedLineInfoForm = new InputRedLineInfoForm((IPolygon4)unionPolygon);
            if (inputRedLineInfoForm.ShowDialog(this) != DialogResult.OK)
                return;


            //提示用户选择保存的路径
            SaveFileDialog_redLine saveFileDialog_redLine = new SaveFileDialog_redLine();
            if (saveFileDialog_redLine.SaveFileDialog.ShowDialog(this) != DialogResult.OK)
                return;

            MyAeMethods.Instance.SetBusyState();
            Application.DoEvents();

            //创建featureclass
            IFeatureClass redLineFeatureClass = MyAeMethods.Instance.CreateRedLineFeatureClass(saveFileDialog_redLine.SaveFileDialog.FileName);

            if (null == redLineFeatureClass)
            {
                MessageBox.Show("无法创建FeatureClass");
                MyAeMethods.Instance.SetDefaultState();
                return;
            }


            //往featureclass中写入数据
            Boolean isAddSuccess = MyAeMethods.Instance.AddDataToFeatureClass(redLineFeatureClass, inputRedLineInfoForm.RedLineRowInfo);


            if (isAddSuccess)
            {
                //向控件中添加图层
                IFeatureLayer toAddFeatureLayer = MyAeMethods.Instance.NewRedFeatureLayer(redLineFeatureClass);
                MyAeMethods.Instance.AddLayer(toAddFeatureLayer);
            }
            else
                MessageBox.Show("没法添加图层", "创建shapefile");

            MyAeMethods.Instance.SetDefaultState();*/
            #endregion

            //获取多边形的外接矩形（旧）
            IEnvelope old_envelop = unionPolygon.Envelope;

            Debug.Print("old_envelop.Width:" + old_envelop.Width);
            Debug.Print("old_envelop.Height:" + old_envelop.Height);
            Debug.Print("old_envelop.LowerLeft.x:" + old_envelop.LowerLeft.X);
            Debug.Print("old_envelop.LowerLeft.y:" + old_envelop.LowerLeft.Y);
            Debug.Print("old_envelop.UpperRight.x:" + old_envelop.UpperRight.X);
            Debug.Print("old_envelop.UpperRight.y:" + old_envelop.UpperRight.Y);

            double old_envelop_width = old_envelop.Width;
            double old_envelop_height = old_envelop.Height;

            //旧envelop左下角坐标
            double lower_left_x = old_envelop.LowerLeft.X;
            double lower_left_y = old_envelop.LowerLeft.Y;


            #region 弹出对话框让用户选择单位和要切割的正方形的长度
            string unit = string.Empty;//单位
            int length = 0;//切割的长方形长度
            Choose_unit choose_unit = new Choose_unit();
            if (choose_unit.ShowDialog() == DialogResult.OK)
            {
                Debug.Print("choose_unit.GetUnit:" + choose_unit.GetUnit);
                Debug.Print("choose_unit.GetLength:" + choose_unit.GetLength);
                unit = choose_unit.GetUnit;
                length = Convert.ToInt32(choose_unit.GetLength);
            }
            else
                return;

            if (unit == "米")
            {
                //length = length;
            }
            else if (unit == "公里")
            {
                length = length * 1000;
            }
            #endregion


            #region 构造一个新的矩形
            int new_envelop_width = Convert.ToInt32(old_envelop_width / length) * length + length;
            int new_envelop_height = Convert.ToInt32(old_envelop_height / length) * length + length;

            Debug.Print("new_envelop_width构建前:" + new_envelop_width.ToString());
            Debug.Print("new_envelop_height构建前:" + new_envelop_height.ToString());

            Envelope new_envelop = new EnvelopeClass();
            new_envelop.PutCoords(lower_left_x, lower_left_y, lower_left_x + Convert.ToDouble(new_envelop_width), lower_left_y + Convert.ToDouble(new_envelop_height));

            Debug.Print("new_envelop.Width构建后：" + new_envelop.Width.ToString());
            Debug.Print("new_envelop.Height构建后:" + new_envelop.Height.ToString());
            #endregion



            //根据新的envelop的长和宽，构建n个面积相等的正方形，保存到一个新的shp文件中，一个正方形是一条记录
            List<IEnvelope> envelop_list = new List<IEnvelope>();
            double new_lower_left_x = new_envelop.LowerLeft.X;
            double new_lower_left_y = new_envelop.LowerLeft.Y;

            double test_x = new_lower_left_x;
            double text_y = new_lower_left_y;

            //List<double> lowerLeft_point_x_list = new List<double>();
            //List<double> lowerLeft_point_y_list = new List<double>();
            //List<double> upperright_point_list = new List<double>();
            MyAeMethods.Instance.SetBusyState();

            //从左下角开始构建,从左到右，从下到上
            for (int j = 0; j < new_envelop_height / length; j++)//y方向
            {
                Debug.Print("---------------------------------");
                for (int i = 0; i < new_envelop_width / length; i++)//x方向
                {
                    IEnvelope envelop = new EnvelopeClass();
                    envelop.PutCoords(new_lower_left_x, new_lower_left_y, new_lower_left_x + length, new_lower_left_y + length);
                    Debug.Print(string.Format("{0}   {1}   {2}   {3}", new_lower_left_x - test_x, new_lower_left_y - text_y, new_lower_left_x + length - test_x, new_lower_left_y + length - text_y));
                    //Debug.Print(string.Format("{0}   {1}   {2}   {3}", new_lower_left_x , new_lower_left_y , new_lower_left_x + length , new_lower_left_y + length ));
                    new_lower_left_x += length;
                    envelop_list.Add(envelop);
                }
                new_lower_left_y += length;
                new_lower_left_x = new_envelop.LowerLeft.X;//还原
                Debug.Print("---------------------------------");
            }



            Debug.Print("envelop_list.Count:" + envelop_list.Count.ToString());

            MyAeMethods.Instance.SetDefaultState();

            string savePath1 = System.IO.Path.GetDirectoryName(openfileDialog.FileName) + "\\" + System.IO.Path.GetFileNameWithoutExtension(openfileDialog.FileName) + "_切割前_" + MyMethods.Date_time_suffix();

            Debug.Print("savePath1:" + savePath1);

            //创建featureclass（空的，里面没有数据）
            IFeatureClass featureClass_no_clip = MyAeMethods.Instance.CreateRedLineFeatureClass(savePath1);

            if (null == featureClass_no_clip)
            {
                MessageBox.Show("无法创建空的FeatureClass，请尝试将保存的shp起另外一个名字。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MyAeMethods.Instance.SetDefaultState();
                return;
            }

            MyAeMethods.Instance.SetBusyState();

            List<RedLineRowInfo> redLineRowInfo_list = new List<RedLineRowInfo>();
            foreach (var envelop in envelop_list)
            {
                //注意坐标系
                RedLineRowInfo redLineRowInfo = new RedLineRowInfo(MyAeMethods.Instance.EnvelopToPolygonClass(envelop, MyAeMethods.Instance.GetSpatialReference_from_featureClass(featureClass)), string.Empty, string.Empty, string.Empty);
                redLineRowInfo_list.Add(redLineRowInfo);
            }


            //往featureclass中写入数据
            Boolean isAddSuccess = MyAeMethods.Instance.AddDatasToFeatureClass(featureClass_no_clip, redLineRowInfo_list.ToArray());

            Application.DoEvents();

            IFeatureClass clip_featureClass = null;

            string savePath2 = System.IO.Path.GetDirectoryName(openfileDialog.FileName) + "\\" + System.IO.Path.GetFileNameWithoutExtension(openfileDialog.FileName) + "_" + string.Format("{0}x{1}{2}", length.ToString(), length.ToString(), unit) + "_" + MyMethods.Date_time_suffix();


            if (isAddSuccess == false)
            {
                MessageBox.Show("往空的FeatureClass中添加数据失败!可能在添加某一条记录时出现错误。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MyAeMethods.Instance.SetDefaultState();
                return;
            }
            else
            {
                //调用gp clip工具切割
                clip_featureClass = MyAeMethods.Instance.Clip_GP(featureClass_no_clip, featureClass, savePath2);
            }


            MyAeMethods.Instance.SetDefaultState();
            if (null != clip_featureClass)
                MessageBox.Show("切割成功！结果shp文件在:\n" + savePath2, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show("切割失败！可能是gp clip工具问题", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }



        //基准地价系统某一功能(改进界面)
        private void 分割图层改进20120810ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_clip_main form_clip_main = new Form_clip_main();
            form_clip_main.ShowDialog();
        }
    }
}
